package com.game.dongzhao.view;

import com.game.dongzhao.DongZhaoApplication;
import com.game.dongzhao.bean.BossFight;
import com.game.dongzhao.bean.CopyWriter;
import com.game.dongzhao.bean.Player;
import com.game.dongzhao.util.ResolveUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Font;
import javafx.stage.Stage;


import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static com.game.dongzhao.DongZhaoApplication.logger;

/**
 * 主界面
 */
public class MainView {

    /**
     * 文案区域
     */
    @FXML
    private TextArea copyWriteText;

    /**
     * 输入框
     */
    @FXML
    private TextField inputText;

    /**
     * 主大图
     */
    @FXML
    private ImageView mainImg;

    /**
     * 地图（右侧）
     */
    @FXML
    private ImageView mapImg;

    /**
     * 玩家信息（右下
     */
    @FXML
    private TextArea playerInfo;

    /**
     * 输入框提交按钮
     */
    @FXML
    private Button submitBtn;

    /**
     * 下一步按钮
     */
    @FXML
    private Button goNextBtn;

    /**
     * 自动播放按钮
     */
    @FXML
    private Button autoGoNextBtn;

    /**
     * 跳转大图界面
     */
    @FXML
    private Button goImageViewBtn;

    /**
     * 跳转支线界面
     */
    @FXML
    private Button goAsideBtn;

    /**
     * 打开知识卡片界面
     */
    @FXML
    private Button goKnowledgeCardBtn;

    /**
     * 跳转地图大图界面
     */
    @FXML
    private Button goMapViewBtn;

    /**
     * 五项boss战道具
     */
    @FXML
    private CheckBox item_xjg;
    @FXML
    private CheckBox item_mhq;
    @FXML
    private CheckBox item_fbdp;
    @FXML
    private CheckBox item_hmj;
    @FXML
    private CheckBox item_zl;
    ;
    /**
     * 文案
     */
    private CopyWriter copyWrite;

    /**
     * 文案时钟
     */
    private int copyWriteClock;

    /**
     * 文案时钟
     */
    private int mapClock;

    /**
     * 上一个问题
     */
    private String lastQuestion;

    /**
     * 当前显示的图片
     */
    public static String nowMainImage = "";

    /**
     * 当前显示的地图
     */
    public static String nowMapImage = "";

    public MainView() throws IOException {
    }

    /**
     * 初始化
     */
    @FXML
    public void initialize() throws InterruptedException, IOException {
        /**文案区文本*/
        this.getCopyWriteText().setEditable(false);
        this.getCopyWriteText().setWrapText(true);
        this.getCopyWriteText().setText("");
        // 玩家信息初始化
        this.getPlayerInfo().setEditable(false);
        this.getPlayerInfo().appendText("领队经验值 : " + Player.manageExp + "\n");
        this.getPlayerInfo().appendText("实习经验值 : " + Player.practiceExp + "\n");
        this.getPlayerInfo().appendText("玩家等级 :" + Player.level);
        // 时钟初始化
        this.initMapClock();
        this.initCopyWriteClock();
        // 文案初始化
        this.setCopyWrite(new CopyWriter());
        this.getCopyWrite().scanCopyWrite();
        // 道具勾选禁用
        this.getItem_xjg().setDisable(true);
        this.getItem_mhq().setDisable(true);
        this.getItem_fbdp().setDisable(true);
        this.getItem_hmj().setDisable(true);
        this.getItem_zl().setDisable(true);
        // 图像初始化
        this.getMainImg().setImage(new Image("file:assert/img/main/Map1-1/init1.jpg", false));
        this.getMapImg().setImage(new Image("file:assert/img/main/Map1-1/init2.jpeg", false));
        // 禁止提交输入
        this.getSubmitBtn().setDisable(true);
        logger.log(System.Logger.Level.INFO, "主界面初始渲染完成");
        // 字体大小改变
        this.getPlayerInfo().setFont(new Font(15.0));
        this.getCopyWriteText().setFont(new Font(15.0));
        this.getInputText().setFont(new Font(15.0));
    }

    /**
     * 提交输入文本并执行处理
     *
     * @param event
     */
    @FXML
    public void submitInput(ActionEvent event) {
        logger.log(System.Logger.Level.INFO, "玩家提交输入");
        List<Object> resolveResult = new ArrayList<>();
        // 仅在需要输入情况下
        if (this.getGoNextBtn().isDisable()) {
            // 提交问题与答案
            if (this.getLastQuestion().matches("》.*\\?\n")) {
                resolveResult = ResolveUtil.questionResolve(this.getLastQuestion(), this.getInputText().getText());
            } else if (this.getLastQuestion().matches("（.*）\n")) {
                resolveResult = ResolveUtil.actionResolve(this.getLastQuestion(), this.getInputText().getText());
            } else {
                resolveResult.add(0);
                resolveResult.add("异常，不存在的问题");
            }
            // 清除输入 输出结果
            this.getInputText().setText("");
            this.getCopyWriteText().appendText(resolveResult.get(1).toString());
            // 文物被抢走强制退出
            if(resolveResult.get(1).toString().equals("》你未获得道具栅栏，盗墓贼成功带着文物从门口离开\n》游戏失败！！文物被盗墓贼盗走，发掘行动未完成，游戏结束！\n"))System.exit(0);
            // 结果正确的话 允许推进
            if ((Boolean) resolveResult.get(0)) {
                // 数据校正 只有？题加经验
                if (this.getLastQuestion().matches("》.*\\?\n")) {
                    Player.increasePracticeExp(10);
                    Player.updateLevel();
                    this.updatePlayerInfo();
                }
                // 切回行动模式
                this.getSubmitBtn().setDisable(true);
                this.getGoNextBtn().setDisable(false);
            } else {
                Player.declinePracticeExp(10);
                Player.updateLevel();
                this.updatePlayerInfo();
                // 仅问题切回行动模式
                if ((int) resolveResult.get(2) == 0) {
                    this.getSubmitBtn().setDisable(true);
                    this.getGoNextBtn().setDisable(false);
                }
            }
        }
    }

    /**
     * 流程推进
     *
     * @param event
     */
    @FXML
    public void goNext(ActionEvent event) {
        logger.log(System.Logger.Level.INFO, "玩家请求下一步 , mapClock : " + mapClock + " , copyWriteClock : " + copyWriteClock);
        // 下一步要打出的句子
        String nextString = this.getCopyWrite().getAllTxt()[mapClock][copyWriteClock] + "\n";
        // 切换主图片
        String nextImg = ResolveUtil.switchMainImage(nextString);
        if (nextImg != "" && nextImg.length() != 0) {
            this.getMainImg().setImage(new Image(nextImg));
            // ImageDetailsView.mainImageUrl = nextImg;
            logger.log(System.Logger.Level.INFO, "切换图片到" + nextImg);
        }
        // 加入到文本输出缓冲区
        if (!nextString.equals(null + "\n")) this.getCopyWriteText().appendText(nextString);
        /** 各种类型的文本类型判断与相关动作执行*/
        // 该地图文案已结束
        if (copyWriteClock == this.getCopyWrite().getAllTxt()[mapClock].length || this.getCopyWrite().getAllTxt()[mapClock][copyWriteClock] == null) {
            logger.log(System.Logger.Level.INFO, "该地图文案结束");
            this.getCopyWriteText().clear();
            this.mapClockRun();
            this.initCopyWriteClock();
        }
        // 问句
        else if (nextString.matches("》.*\\?\n")) {
            logger.log(System.Logger.Level.INFO, "进入问句");
            this.setLastQuestion(nextString);
            // 时钟后移到第一个选项
            this.copyWriteClockRun();
            nextString = this.getCopyWrite().getAllTxt()[mapClock][copyWriteClock] + "\n";
            do {
                // 输出选项
                this.getCopyWriteText().appendText(nextString);
                // 时钟后移
                this.copyWriteClockRun();
                nextString = this.getCopyWrite().getAllTxt()[mapClock][copyWriteClock] + "\n";
            } while (nextString.matches("[a-z]\\..*\n"));
            // 等待返回回答 禁用下一步
            this.getGoNextBtn().setDisable(true);
            this.getSubmitBtn().setDisable(false);
        }
        // 输入动作的提示
        else if (nextString.matches("（.*）\n")) {
            logger.log(System.Logger.Level.INFO, "进入动作句");
            this.setLastQuestion(nextString);
            // 等待返回回答 禁用下一步
            this.getGoNextBtn().setDisable(true);
            this.getSubmitBtn().setDisable(false);
            this.copyWriteClockRun();
        }
        // 游戏结束
        else if (mapClock == 16) {
            logger.log(System.Logger.Level.INFO, "游戏结束");
        }
        // 正常下一句
        else {
            this.copyWriteClockRun();
        }
        // exp提示
        if (Player.checkPlayerExp().length() != 0) this.getCopyWriteText().appendText(Player.checkPlayerExp());
        // boss战物品检查
        this.checkBossFightItem();
    }

    /**
     * 自动播放/加速播放
     *
     * @param event
     */
    @FXML
    public void autoGoNext(ActionEvent event) {
        logger.log(System.Logger.Level.INFO, "进入自动播放");
        while (true) {
            // 激活按钮直至抵达问题阶段
            this.goNextBtn.fire();
            if (this.getGoNextBtn().isDisable()) break;
//            try {
//                TimeUnit.MILLISECONDS.sleep(this.getCopyWrite().getAllTxt()[mapClock][copyWriteClock].length() * 100);
//            } catch (InterruptedException e) {
//                logger.log(System.Logger.Level.ERROR, "延时出现错误");
//            }
        }
    }

    /**
     * 显示图片详细
     *
     * @param event
     */
    @FXML
    public void goImageView(ActionEvent event) {
        logger.log(System.Logger.Level.INFO, "进入大图显示");
        try {
            Stage imageStage = new Stage();
            ImageDetailsView.mainImageUrl = this.getMainImg().getImage().getUrl();
            new DongZhaoApplication().start(imageStage, "显示图片细节", "image-view.fxml");
        } catch (IOException e) {
            logger.log(System.Logger.Level.ERROR, "显示图片失败");
            e.printStackTrace();
        }
    }

    /**
     * 显示地图图片详细
     *
     * @param event
     */
    @FXML
    public void goMapView(ActionEvent event) {
        logger.log(System.Logger.Level.INFO, "进入地图大图显示");
        try {
            Stage imageStage = new Stage();
            ImageDetailsView.mainImageUrl = this.getMapImg().getImage().getUrl();
            new DongZhaoApplication().start(imageStage, "显示地图图片细节", "image-view.fxml");
        } catch (IOException e) {
            logger.log(System.Logger.Level.ERROR, "显示图片失败");
            e.printStackTrace();
        }
    }

    /**
     * 前往支线
     * @param event
     */
    @FXML
    public void goAside(ActionEvent event) {
        this.getGoAsideBtn().setDisable(true);
        try {
            logger.log(System.Logger.Level.INFO,"打开支线任务界面");
            new DongZhaoApplication().start(new Stage(),"支线任务界面","aside-view.fxml");
        } catch (IOException e) {
            logger.log(System.Logger.Level.ERROR,"转到支线任务出现错误");
            e.printStackTrace();
        }
    }

    /**
     * boss战物品获得状态
     */
    @FXML
    public void checkBossFightItem(){
        if(BossFight.item_zl)this.getItem_zl().setSelected(true);
        if(BossFight.item_hmj)this.getItem_hmj().setSelected(true);
        if(BossFight.item_xjg)this.getItem_xjg().setSelected(true);
        if(BossFight.item_fbdp)this.getItem_fbdp().setSelected(true);
        if(BossFight.item_mhq)this.getItem_mhq().setSelected(true);
    }

    /**
     * 打开知识卡片
     * @param event
     */
    @FXML
    public void goKnowledgeCard(ActionEvent event) {

    }

    /**
     * 玩家信息实时刷新
     */
    public void updatePlayerInfo() {
        // 视图重新刷新
        this.getPlayerInfo().clear();
        this.getPlayerInfo().appendText("领队经验值 : " + Player.manageExp + "\n");
        this.getPlayerInfo().appendText("实习经验值 : " + Player.practiceExp + "\n");
        this.getPlayerInfo().appendText("玩家等级 :" + Player.level);
        // 文件刷新
        File playerData = new File("./assert/playerData.dat");
        try {
            OutputStream outData = new FileOutputStream(playerData);
            DataOutputStream outDataStream = new DataOutputStream(outData);
            outDataStream.writeInt(Player.manageExp);
            outDataStream.writeInt(Player.practiceExp);
            outDataStream.writeInt(Player.level);
            outDataStream.close();
            outData.close();
        } catch (IOException e) {
            logger.log(System.Logger.Level.ERROR, "更新文件数据错误");
        }
    }

    /**
     * 初始化文案时钟
     */
    public void initCopyWriteClock() {
        this.copyWriteClock = 0;
    }

    /**
     * 时钟运行
     */
    public void copyWriteClockRun() {
        this.copyWriteClock++;
    }

    /**
     * 初始化地图时钟
     */
    public void initMapClock() {
        this.setMapClock(Player.lastMapClock);
    }

    /**
     * 时钟运行
     */
    public void mapClockRun() {
        this.mapClock++;
    }

    public TextArea getCopyWriteText() {
        return copyWriteText;
    }

    public void setCopyWriteText(TextArea copyWriteText) {
        this.copyWriteText = copyWriteText;
    }

    public TextField getInputText() {
        return inputText;
    }

    public void setInputText(TextField inputText) {
        this.inputText = inputText;
    }

    public ImageView getMainImg() {
        return mainImg;
    }

    public void setMainImg(ImageView mainImg) {
        this.mainImg = mainImg;
    }

    public ImageView getMapImg() {
        return mapImg;
    }

    public void setMapImg(ImageView mapImg) {
        this.mapImg = mapImg;
    }

    public TextArea getPlayerInfo() {
        return playerInfo;
    }

    public void setPlayerInfo(TextArea playerInfo) {
        this.playerInfo = playerInfo;
    }

    public Button getSubmitBtn() {
        return submitBtn;
    }

    public void setSubmitBtn(Button submitBtn) {
        this.submitBtn = submitBtn;
    }

    public Button getGoNextBtn() {
        return goNextBtn;
    }

    public void setGoNextBtn(Button goNextBtn) {
        this.goNextBtn = goNextBtn;
    }

    public CopyWriter getCopyWrite() {
        return copyWrite;
    }

    public void setCopyWrite(CopyWriter copyWrite) {
        this.copyWrite = copyWrite;
    }

    public int getCopyWriteClock() {
        return copyWriteClock;
    }

    public void setCopyWriteClock(int copyWriteClock) {
        this.copyWriteClock = copyWriteClock;
    }

    public String getLastQuestion() {
        return lastQuestion;
    }

    public void setLastQuestion(String lastQuestion) {
        this.lastQuestion = lastQuestion;
    }

    public CheckBox getItem_xjg() {
        return item_xjg;
    }

    public void setItem_xjg(CheckBox item_xjg) {
        this.item_xjg = item_xjg;
    }

    public CheckBox getItem_mhq() {
        return item_mhq;
    }

    public void setItem_mhq(CheckBox item_mhq) {
        this.item_mhq = item_mhq;
    }

    public CheckBox getItem_fbdp() {
        return item_fbdp;
    }

    public void setItem_fbdp(CheckBox item_fbdp) {
        this.item_fbdp = item_fbdp;
    }

    public CheckBox getItem_hmj() {
        return item_hmj;
    }

    public void setItem_hmj(CheckBox item_hmj) {
        this.item_hmj = item_hmj;
    }

    public CheckBox getItem_zl() {
        return item_zl;
    }

    public void setItem_zl(CheckBox item_zl) {
        this.item_zl = item_zl;
    }

    public Button getAutoGoNextButton() {
        return autoGoNextBtn;
    }

    public void setAutoGoNextButton(Button autoGoNextButton) {
        this.autoGoNextBtn = autoGoNextButton;
    }

    public Button getGoImageViewBtn() {
        return goImageViewBtn;
    }

    public void setGoImageViewBtn(Button goImageViewBtn) {
        this.goImageViewBtn = goImageViewBtn;
    }

    public Button getGoAsideBtn() {
        return goAsideBtn;
    }

    public void setGoAsideBtn(Button goAsideBtn) {
        this.goAsideBtn = goAsideBtn;
    }

    public Button getGoKnowledgeCardBtn() {
        return goKnowledgeCardBtn;
    }

    public void setGoKnowledgeCardBtn(Button goKnowledgeCardBtn) {
        this.goKnowledgeCardBtn = goKnowledgeCardBtn;
    }

    public Button getGoMapViewBtn() {
        return goMapViewBtn;
    }

    public void setGoMapViewBtn(Button goMapViewBtn) {
        this.goMapViewBtn = goMapViewBtn;
    }

    public int getMapClock() {
        return mapClock;
    }

    public void setMapClock(int mapClock) {
        this.mapClock = mapClock;
    }
}
